import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "antd-mobile";
import styles from "./LocList.module.less";
import { createAction } from "@common/utils";
import { PUSH_PAGE_STACK } from "@store/global-state/action-types";
import {
  SAGA_STOCKTAKING_LOAD_LOC_LIST,
} from "@store/stocktaking/saga-types";

const doneStyle = {
  backgroundColor: "#00B578",
  color: "#FFF",
};

const LocList = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const dispatch = useDispatch();
  const locList = useSelector((state) => state.stocktaking.locList);

  useEffect(() => {
    dispatch(
      createAction(SAGA_STOCKTAKING_LOAD_LOC_LIST, {
        id: searchParams.get("id"),
      })
    );
  }, []);

  const handleClick = (record) => {
    let orderType = searchParams.get("type");
    enterOpsPage(
      orderType,
      record.locationId,
      record.locationCode,
      record.status
    );
  };

  const enterOpsPage = (type, locationId, locationCode, status) => {
    let path = `/app/stocktaking/${
      type === "BLIND" ? "blind-ops/item-info" : "open-ops/item-info"
    }?id=${searchParams.get(
      "id"
    )}&locationId=${locationId}&locationCode=${locationCode}&status=${status}`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  return (
    <>
      <div style={{ marginTop: "45px", marginBottom: "65px" }}>
        <div className={styles["blk-title"]}>请选择库位</div>
        <div className={styles["loc-blk"]}>
          <Grid columns={2} gap={8}>
            {locList?.map((record, idx) => (
              <Grid.Item key={idx}>
                <a
                  className={styles["loc-link"]}
                  style={record.status === "DONE" ? doneStyle : null}
                  onClick={() => handleClick(record)}
                >
                  {record.locationCode}
                </a>
              </Grid.Item>
            ))}
          </Grid>
        </div>
      </div>
    </>
  );
};

export default LocList;
